//
//  GameControl.swift
//  DiceGame
//
//  Created by tanwz on 16/11/17.
//  Copyright © 2016年 tanwz. All rights reserved.
//

import UIKit


protocol GameDelegate {
    func didRoll(side: Int)
    func willMove(from: Int, to: Int, isLinear: Bool)
    func gameStart()
    func gameOver()
}

class GameControl {
    var delegate: GameDelegate?
    private(set) var currentBoard: Int = 0
    private(set) var totalStep = 0
    private(set) var started = false
    private(set) var boards: [Int]
    let boardCount = 25
    
    private var dice: Dice
    private var stepToMove = 0
    
    init() {
        dice = Dice(sides: 6, generator: LinearCongruentialGenerator())
        
        boards = Array(repeating: 0, count: boardCount)
        boards[2] = +8; boards[5] = +11; boards[8] = +9; boards[9] = +2
        boards[13] = -10; boards[18] = -11; boards[21] = -2; boards[23] = -8
    }
    
    func startGame() {
        if started {
            return
        }
        
        currentBoard = 0
        totalStep = 0
        stepToMove = 0;
        started = true;
        
        delegate?.gameStart()
    }
    
    func roll() {
        if !started {
            return
        }
        
        totalStep += 1
        let ret = dice.roll()
        delegate?.didRoll(side: ret)
        
        startMove(step: ret)
    }
    
    func commit() {
        if !started {
            return
        }
        
        if stepToMove != 0 {
            currentBoard += stepToMove
            stepToMove = 0
            judge()
        }
    }
    
    private func startMove(step: Int, isLinear:Bool = false) {
        stepToMove = step;
        delegate?.willMove(from: currentBoard, to: currentBoard + step, isLinear: isLinear)
    }
    
    func judge() {
        if currentBoard >= boardCount - 1 {
            started = false
            delegate?.gameOver()
        } else {
            if boards[currentBoard] != 0 {
                startMove(step: boards[currentBoard], isLinear: true)
            }
        }
    }
}
